package kpi.javatraining6.gnatiuk.palindrome;

import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;
/**
 * 
 * @author Surp
 *
 */
public class Palindrome {
	private static final int MIN_PALINDROME_LENGTH = 3;// minimum length of a palindrome

	public static void main(String[] args) {
		System.out.println("Enter a palindrome");
		Scanner in = new Scanner(System.in);
		System.out.format("palindromes: %s",getPalindroms(in.nextLine()));
	}

	/**
	 * method get all possible palindromes in the row
	 * 
	 * @param s
	 * @return collection of palindromes
	 */
	public static Set<String> getPalindroms(String s) {
		Set<String> palindroms = new TreeSet<>();
		
		String row = s.replaceAll(" ", "").toLowerCase();
		String buffer = "";
		for (int i = 0; i < row.length() - (MIN_PALINDROME_LENGTH - 1); i++) {
			int currentSymbol = i + (MIN_PALINDROME_LENGTH - 1);
			while (currentSymbol <= row.length()) {
				currentSymbol = row.indexOf(row.substring(i, i + 1), currentSymbol);
				if (currentSymbol < 0) {
					break;
				}
				currentSymbol++;
				buffer = row.substring(i, currentSymbol);

				if (isPalindrome(buffer)) {
					palindroms.add(buffer);
				}
			}
		}

		return palindroms;
	}

	/**
	 * method checks if row is palindrome
	 * 
	 * @param s
	 * @return
	 */
	private static boolean isPalindrome(String s) {
		char[] arr = s.toCharArray();

		for (int i = 0; i < arr.length / 2; i++) {
			if (arr[i] != arr[arr.length - 1 - i]) {
				return false;
			}
		}

		return true;
	}
}

